package com.cn.demo4.util;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器
 * /* 代表所有路径都拦截
 */

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.乱码问题
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("");

        //登录，注册页面不能拦截，只能拦截后台访问地址
        String path = req.getServletPath();
//        System.out.println(path);
        //只要是以/admin开头的后台接口，都要过滤拦截
        if(path.startsWith("/admin/")){
            HttpSession session = req.getSession();
            String key = req.getParameter("loginPhone");
            String phone = (String) session.getAttribute(key);
            //2.判断是否登录
            if(phone == null){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result","noLogin");
                resp.getWriter().println(jsonObject);
            }else {
                //放行
                filterChain.doFilter(req, resp);
            }
        }else{
            //放行
            filterChain.doFilter(req, resp);
        }

    }
    @Override
    public void destroy() {
    }
}
